import sys
sys.path.append("..")
import cv2
import utils.raster as raster
import numpy as np
import matplotlib.pyplot as plt

def findUnicomArea(img):
    ret,threshold = cv2.threshold(img.astype(np.float),0,1,cv2.THRESH_BINARY)
    # img_flag = np.zeros(threshold.shape,np.int8)
    image, contours, hierarchy = cv2.findContours(threshold.astype(np.uint8),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    img_flag = cv2.drawContours(image, contours, 3, (0,255,0), 3)
    print(len(contours))
    # for item in contours:
    #     print(item.shape)
    # plt.imshow(img_flag)
    # plt.show()
    # print(np.min(img_flag))
    # plt.imshow(threshold)
    # plt.show()
    # count = 0
    # findpoint = []
    # coutours = []
    # #首先遍历图像找到所有的联通区
    # for x in range(0,threshold.shape[0]-1):
    #     for y in range(0,threshold.shape[1]-1):
    #         if(threshold[x][y] == 0 and img_flag[x][y] == 0):

    #             count += 1
    #             #新增一个联通区存储点
    #             coutours.append([])
    #             img_flag[x][y] = count
    #             findpoint.append((x,y))
    #         while len(findpoint) > 0:
    #             xx,yy = findpoint.pop()
    #             #上面
    #             if threshold[xx-1][yy] == 0 and img_flag[xx-1][yy] == 0:
    #                 findpoint.append((xx-1,yy))
    #                 img_flag[xx-1][yy] = count
    #                 coutours[count - 1].append([xx, yy, img_flag[x][y]])
    #             #下面
    #             if threshold[xx + 1][yy] == 0 and img_flag[xx + 1][yy] == 0:
    #                 findpoint.append((xx + 1, yy))
    #                 img_flag[xx+1][yy] = count
    #                 coutours[count - 1].append([xx, yy, img_flag[x][y]])
    #             #左面
    #             if threshold[xx][yy-1] == 0 and img_flag[xx][yy-1] == 0:
    #                 findpoint.append((xx, yy-1))
    #                 img_flag[xx][yy-1] = count
    #                 coutours[count - 1].append([xx, yy, img_flag[x][y]])
    #             #右面
    #             if threshold[xx][yy+1] == 0 and img_flag[xx][yy+1] == 0:
    #                 findpoint.append((xx, yy+1))
    #                 img_flag[xx][yy+1] = count
    #                 coutours[count - 1].append([xx, yy, img_flag[x][y]])

    # desCoutous = np.empty(len(coutours),np.object)
    # for num in range(len(coutours)):
    #     #将分离后的图像提取出来。计算出联通区所在的范围
    #     tmp = np.mat(coutours[num])
    #     minX = np.min(tmp[:,0])
    #     maxX = np.max(tmp[:,0])
    #     minY = np.min(tmp[:,1])
    #     maxY = np.max(tmp[:,1])
    #     desCoutous[num] = img[minX:maxX,minY:maxY]
    # return desCoutous

if __name__ == '__main__':
    info,data = raster.open("/mnt/fire/Extract/date/date_2013001.tif")
    findUnicomArea(data)